package czk.concrent.enjoyModelWithNotLock.unsafe;

import sun.misc.Unsafe;

import java.util.ArrayList;
import java.util.List;

/** 模拟实现AtomicInteger
 * @Author:ChenZhangKun
 * @Date: 2020/6/20 18:02
 */
public class MyAtomicIntegerDemo {
    public static void main(String[] args) {
        // 初始值为500元
        MyAtomicInteger myAtomicInteger=new MyAtomicInteger(500);
        Account.demo(myAtomicInteger);
        System.out.println(myAtomicInteger.getBalance());
        System.out.println(myAtomicInteger.getBalance());
    }

}
class MyAtomicInteger implements Account{
    // 保护的对象
    private volatile int value;
    // 保护对象域的偏移量
    private static long valueOffset;
    // 声明unsafe对象
    static final Unsafe UNSAFE;
     static {
         UNSAFE=UnsafeAccessor.getUnsafe();
         try {
            valueOffset= UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
         } catch (NoSuchFieldException e) {
             e.printStackTrace();
         }
     }
     public int getValue(){
         return value;
     }
     // 相减
     public void decrement(int count){
         // cas操作
         while (true){
             int pre=this.value;
             int next=this.value-count;
             // unsafe对象进行cas操作 相当于AtomicInteger的compareAndSet()方法
             // AtomicInteger的底层实现
             if (UNSAFE.compareAndSwapInt(this,valueOffset,pre,next)){
                 break;
             }
         }
     }

    @Override
    public int getBalance() {
        return this.getValue();
    }

    @Override
    public void withDraw(Integer count) {
        this.decrement(count);
    }
    // 构造方法赋予初始值

    public MyAtomicInteger(int value) {
        this.value = value;
    }
}
interface Account{

    // 获取余额
    int getBalance();
    // 取款
    void withDraw(Integer count);
    static void demo(Account account){
        // 创建1000个线程
        // 接收集合
        List<Thread> listThread=new ArrayList<>(1000);
        for (int i = 0; i < 3; i++) {
            listThread.add(new Thread(()->{
                account.withDraw(100);
            }));
        }
        // 启动线程
        for (Thread thread : listThread) {
            thread.start();
        }
        // 等待线程运行完毕
        for (Thread thread : listThread) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
